package com.lagou.java.config;

import com.lagou.java.io.Resources;
import com.lagou.java.pojo.Configration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configration configration;

    public XMLConfigBuilder () {
        this.configration = new Configration();
    }

    /**
     * 将配置文件进行解析
     * @param inputStream
     * @return
     */
    public Configration parseConfig (InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> selectNodes = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        selectNodes.forEach(node -> {
            String name = node.attributeValue("name");
            String value = node.attributeValue("value");
            properties.setProperty(name, value);
        });

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configration.setDataSource(comboPooledDataSource);

        List<Element> list = rootElement.selectNodes("//mapper");
        for (Element element : list) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configration;
    }
}
